//
//  HMUserAccountViewModel.swift
//  Weibo
//
//  Created by Apple on 2017/7/12.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
//  封装OAuth登录的相关网络请求
class HMUserAccountViewModel: NSObject {

    //  为了数据共享，设置单例模型访问用户模型数据
    static let sharedUserAccount = HMUserAccountViewModel()
    
    //  构造函数私有化
    private override init() {
        super.init()
        //  加载沙盒文件对象
        userAccount = HMUserAccount.loadUserAccount()
    }
    
    //  用户模型
    var userAccount: HMUserAccount?
    
    //  是否登录
    var isLogin: Bool {
        return accessToken != nil
    }
    
    //  获取token的时候需要判断是否为空和不为空还要判断是否过期
    var accessToken: String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        if userAccount?.expiresDate?.compare(Date()) == .orderedDescending {
            //  没有过期
            return token
        } else {
            //  过期返回token设置为nil
            return nil
        }
    }
    
    //  根据code获取令牌
    func requestAccesstoken(code: String, callBack: @escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false)
                return
            }
            
            let dic = response as! [String: Any]
            //  字典转模型
            let userAccount = HMUserAccount(dic: dic)
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
        }
    }
    
    //  获取用户信息
    fileprivate func requestUserInfo(userAccount: HMUserAccount, callBack: @escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestUserInfo(access_token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            if error != nil {
                print("error: \(error!)")
                callBack(false)
                return
            }
            let dic = response as! [String: Any]
            userAccount.avatar_large = dic["avatar_large"] as? String
            userAccount.name = dic["name"] as? String
            //  归档用户对象
            userAccount.saveUserAccount()
            //  记录等于用户模型
            self.userAccount = userAccount
            //  登录成功的回调
            callBack(true)
        }
    }
    
    
}
